package org.study.hadoop.md.ch4;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.study.hadoop.md.util.MRDPUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Random;

/**
 * 混排：给定StackOverflow评论的一个大数据集，对每条评论进行匿名化处理，包括：去除记录ID和时间，然后再整个数据集内对记录随机混排
 */
public class AnonymizeDriver extends Configured implements Tool {

    public static class ValueReduce extends Reducer<IntWritable, Text, Text, NullWritable> {
        @Override
        protected void reduce(IntWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            for (Text text : values) {
                context.write(text, NullWritable.get());
            }
        }
    }

    public static class AnonymizeMapper extends Mapper<Object, Text, IntWritable, Text> {
        private IntWritable outKey = new IntWritable();
        private Text outValue = new Text();
        private Random random = new Random();

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            Map<String, String> parsed = MRDPUtils.transformXmlToMap(value.toString());
            if (parsed.size() > 0) {
                StringBuilder sb = new StringBuilder();
                sb.append("<row\t");
                for (Map.Entry<String, String> entry : parsed.entrySet()) {
                    if (entry.getKey().equals("UserId") || entry.getKey().equals("Id")) {

                    } else if (entry.getKey().equals("CreationDate")) {
                        sb.append(entry.getKey() + "=" + 'T' + "\t");
                    } else {
                        sb.append(entry.getKey() + "=" + entry.getValue() + "\t");
                    }
                }
                sb.append(">");
                outKey.set(random.nextInt());
                outValue.set(sb.toString());
                context.write(outKey, outValue);
            }
        }
    }

    @Override
    public int run(String[] args) throws Exception {
        Path outPath = new Path("out");
        Path inPath = new Path("comment.txt");
        FileSystem fs = outPath.getFileSystem(getConf());
        if (fs.exists(outPath)) {
            fs.delete(outPath, true);
        }
        Job job = Job.getInstance(getConf(), "Anonymize");
        job.setJarByClass(AnonymizeDriver.class);
        job.setMapperClass(AnonymizeMapper.class);
        job.setReducerClass(ValueReduce.class);
        job.setNumReduceTasks(10);
        FileInputFormat.addInputPath(job, inPath);
        FileOutputFormat.setOutputPath(job, outPath);

        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(Text.class);

        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new AnonymizeDriver(), args);
        System.exit(res);
    }
}
